<?php 
include("header.inc.php");
include 'auth.inc.php';
?>
<h1>Edit Schema</h1>


<?php

$admin_tables = array(
	"0" => "users",
	"1" => "changes",
	"2" => "access_levels",
);

function validateName($name, $type) {
//echo substr($name, strlen($name)-4);
//echo $name;
 if ($type=="filename" && 
	preg_match("/^[a-zA-Z0-9_\-\.]*$/", $name) && 
	substr($name, strlen($name)-4)==".xsd"){ 
	return true;
 } else if ($type=="tablename" && preg_match("/^[a-zA-Z0-9]*$/", $name)){
 	return true;
 } else return false;
}
function showQuery($query) {
	echo "<div class=\"output\">";
	echo "<h2>Generated Output</h2>";
	echo "<pre>" . $query ."</pre>";
	echo "</div>";

}

$schema_path="/home/ubuntu/drd/its-a-profs-life/schema_files/";
$schema_parser="/home/ubuntu/drd/its-a-profs-life/schema/XSDParser.pl";

/* Get schema files currently availiable from the file ID and create a hash
	table where the file ID make to the file name */
$output = shell_exec('ls -1i "' . $schema_path . '" | grep ".\.xsd$"');
$plain2 = preg_split("/[\n]+/", $output, -1, PREG_SPLIT_NO_EMPTY);
foreach ($plain2 as &$value){
        $value = trim($value);
	 $files[substr($value, 0, strpos($value, " "))] = substr(strstr($value," "),1);
}
//echo "<pre>";
//var_export($files);
//echo "</pre>";
//echo "<p>" . count($files) . "</p>";

/* Check for edit */
if ($_POST['DeleteSelected']=='' &&
        $_POST['Selected']=='' &&
        $_POST['Submit']=='' &&
        $_POST['Switch']=='' &&
	$_POST['Submit2']=='' &&
        $_POST['Gen']=='' &&
        count($_POST)!=0) {
echo "<p>Editing...</p>";
while (list($key, $value) = each($_POST)) {
        if (substr($key, 0, 5)=='edit_' && $value == 'Look Up') {
                $edit_selected = substr($key,5);
		$_GET['input']='form';
	} else if (substr($key, 0, 5)=='edit_' && $value == 'Edit') {
		$edit_selected = $files[substr($key,5)];
		$_GET['input']='';
		$target = $schema_path . $edit_selected;
        } else if (substr($key, 0, 7)=='delete_') {
                continue;
        } else {
                break;
        }
}
//echo $edit_selected;
//echo "<pre>" . var_export($_POST) . "</pre>";
}



/* Connect to database */
include("db.inc.php");
$con = mysql_connect(MYSQL_HOST,MYSQL_USER,MYSQL_PASSWORD);

if (!$con) {
         die ('Error: Could not connect to mySQL server');
}
$mysql = MYSQL_DB;
if (!mysql_select_db($mysql)) {
        die ('Error: Could not connect to mySQL database');
}


/* Get type of input based on input switch */
if ($_POST['Switch']=='Plain Text Input') {
	$_GET['input'] = '';
} else if ($_POST['Switch']=='File Input') {
	$_GET['input'] = 'file';
} else if ($_POST['Switch']=='Form Input') {
	$_GET['input'] = 'form';
}


/* ADD TABLE from FORM INPUT */
if ($_POST['Submit']=='Add New Table') {
echo "<p>Adding...</p>";
$fPK = $_POST['fPK'];
$j=0;
$prim_key = "";
$foreign_key = "";
$nFK=1;

//echo "Primary keys: " . var_dump($fPK);

if (!preg_match("/^[a-zA-Z0-9]*$/", $_POST['tableName'])) {
	echo "</p><p class=\"error-message\">Error: This system only supports table names that are made out of letters (a-z) or numbers</p>";
	$error_exists = true;	
}


$sql = "CREATE TABLE ".mysql_real_escape_string($_POST['tableName']) ."(\n";
$sql = $sql . "ID int(11) NOT NULL AUTO_INCREMENT,\nUNIQUE KEY ID (ID),\n";
for ($i=1; $i<$_POST['num_fields']; $i++){

	if (!preg_match("/^[a-zA-Z0-9]*$/", $_POST['fName_'.$i])) {
		echo "</p><p class=\"error-message\">Error: This system only supports field names that are made out of letters (a-z) or numbers</p>";
		$error_exists = true;
	}

        $sql = $sql . mysql_real_escape_string($_POST['fName_'.$i]). " " . mysql_real_escape_string($_POST['fType_'.$i]) . " " . mysql_real_escape_string($_POST['fFlag_'.$i]);
        if ($i != $_POST['num_fields']-1) {
                $sql = $sql . ",\n";
        }
	if (count($fPK)>0 && $fPK[$j]==$i+1) {
		$prim_key = $prim_key . mysql_real_escape_string($_POST['fName_'.$i]);
		if ($j != count($fPK)-1)
			$prim_key = $prim_key . ", ";
		$j++;
	}
	if ($_POST['fFTab_'.$i]!="" && $_POST['fFCol_'.$i]!="") {
		if ($nFK==0) {
			$foreign_key = $foreign_key . ",\n";
		}
		$foreign_key = $foreign_key . "FOREIGN KEY (" . mysql_real_escape_string($_POST['fName_'.$i]) . ") REFERENCES " . $_POST['fFTab_'.$i] . "(" . $_POST['fFCol_'.$i] . ")";
		$nFK=0;
	}
}
if ($prim_key!="") {
	$sql = $sql . ",\nPRIMARY KEY(" . $prim_key . ")";
}
if ($foreign_key!="") {
	$sql = $sql . ",\n" . $foreign_key;
}
$sql = $sql . ')';
showQuery($sql);
if ($error_exists!=true && mysql_query($sql)) {
        echo "<p>...Done</p>";
} else {
        echo "</p><p class=\"error-message\">Error: Unable to add table: ";
        echo mysql_error() . "</p>";
	$error_exists = true;
}
}





/* Get values and put them in plain[] */
if ($_GET['input']=='form' && ($_POST['Submit2']!='' || $error_exists==true)) {
if (in_array($_POST['origTableName'], $admin_tables) || 
	in_array($_POST['tableName'], $admin_tables)) {
	echo "<p class=\"error-message\">Error: You are not allowed to alter administrative tables</p>";
	$error_exists = true;
} else {



/* Setting up the form to print what was recently printed in it */
$edit_selected = $_POST['origTableName'];
$fPK = $_POST['fPK'];
$plain = array();
$plain[0] = $_POST['tableName'];
//echo var_dump($fPK);
array_push($plain, $_POST['tableName']);
for ($i=0; $i<$_POST['num_fields']; $i++) {
	$plain[$i+1] = array();
	array_push($plain[$i+1], $_POST['fName_'.$i]);
	array_push($plain[$i+1], $_POST['fType_'.$i]);
	array_push($plain[$i+1], $_POST['fFlag_'.$i]);
	if (in_array($i+1 . "-PK",$fPK) || in_array($i+1 . "-NOT",$fPK))
		array_push($plain[$i+1],($i+1)."-PK");
	else
		array_push($plain[$i+1],($i+1)."-NOT");
	array_push($plain[$i+1], $_POST['fFTab_'.$i]);
	array_push($plain[$i+1], $_POST['fFCol_'.$i]);
	array_push($plain[$i+1], $_POST['fFCon_'.$i]);
}




/* Add fields */
if ($_POST['Submit2']=='Add Rows') {
	for ($i=$_POST['num_fields']; $i<($_POST['num_fields']+$_POST['add_fields']); $i++)
		$plain[($i+1)][3] = $i."-NOT";
	$fields = $_POST['num_fields']+$_POST['add_fields'];
} else $fields = $_POST['num_fields'];




/* Delete Fields */
if ($_POST['Submit2']=='Delete Selected Rows') {
echo "<p>Deleting Fields...";
$offset =0;
$fDel = $_POST['fDel'];

/* We're just deleting rows from the table */
for ($i=0; $i<count($fDel); $i++){
	$fields--;
	array_splice($plain, $fDel[$i]+1+$offset, count($plain), array_slice($plain, $fDel[$i]+2+$offset));
	$offset--;
}

echo "<p>...Done</p>";
}



} /* END if statment to protect the administrative tables */


/* Get values from an existing table and put them in plain[] */
} else if ($edit_selected!='') {

/* GET TABLE ATTRIBUTES */
$result2 = mysql_query("SHOW CREATE TABLE $edit_selected");
$table_def = mysql_fetch_row($result2);
$line = $table_def[1];
//echo "<pre>" .$line."</pre>";
$lines = preg_split("/[\n]+/", $line, -1, PREG_SPLIT_NO_EMPTY);
//print_r($lines);
preg_match_all("/CREATE\sTABLE\s`([^`]*)`\s\(/", $lines[0], $matches, PREG_SET_ORDER);
//echo "<hr />";
//print_r($matches);
$plain[0] = $matches[0][1];
$_POST['origTableName'] = $plain[0];
//echo $plain[0];
for ($i=1; $i<count($lines); $i++) {
//echo "<pre>".$lines[$i]."</pre>";
	$plain[$i] = array();
	preg_match_all("/[\s]*`([^`]*)`\s([^\s]*)\s([^,]*)[,]*/", $lines[$i], $matches, PREG_SET_ORDER);
	if (substr($matches[0][3],strlen($matches[0][3])-1)==",")
		$matches[0][3] = substr($matches[0][3], 0, strlen($matched[0][3])-1);	

	if (count($matches)==0) {
		preg_match_all("/[\s]*`([^`]*)`\s([^\s]*)[,]*/", $lines[$i], $matches, PREG_SET_ORDER);
//echo substr($matches[0][2],strlen($matches[0][2])-1); 
		if (substr($matches[0][2],strlen($matches[0][2])-1)==",")
			$matches[0][2] = substr($matches[0][2], 0, strlen($matched[0][2])-1);
	}
//	print_r($matches);
//echo "<hr />";
	if (substr($lines[$i],0,3)!="  `") {
//echo $i;
                break;
        }

	array_push($plain[$i], $matches[0][1]);
	$_POST['foName_'.($i-1)] = $matches[0][1];
	array_push($plain[$i], $matches[0][2]);
	array_push($plain[$i], $matches[0][3]);
	$fields++;
}
if (substr($lines[$i],2,11)=="PRIMARY KEY") {
	$prim_keys = preg_split("/`/",$lines[$i], -1, PREG_SPLIT_NO_EMPTY);
//echo "<br />PRIMARY KEYS: ";
//print_r($prim_keys);
	$i++;
}
$unique_keys = array();
for ( ; $i < count($lines); $i++) {
	preg_match_all("/\s\sUNIQUE\sKEY\s`([^`]*)`[^,]*[,]*/", $lines[$i], $matches, PREG_SET_ORDER);
//	 echo var_dump($matches);
	if (count($matches)==0)
		break;
	array_push($unique_keys,$matches[0][1]);
}
//echo "<pre>";
//echo var_export($unique_keys);
//echo var_export($plain);
//echo "</pre>";

for ($j=1; $j<count($plain); $j++) {
	if (in_array($plain[$j][0], $prim_keys))
		array_push($plain[$j], "$j-PK");
	else
		array_push($plain[$j], "$j-NOT");
//	$tmp = preg_split("/`/",$lines[$i], -1, PREG_SPLIT_NO_EMPTY);
//echo "<p>".$tmp[1]."</p>";

	if (in_array($plain[$j][0],$unique_keys)) {
		$plain[$j][2] = "UNIQUE " .$plain[$j][2];
//		$i++;
	}
}
//while (substr($lines[$i],2,10)!="CONSTRAINT")
//	$i++;
for (; $i<count($lines); $i++) {
//while ($i<count($lines)) {
	$regExp = '/\s+CONSTRAINT `([^`]*)` FOREIGN KEY \(`([^`]*)`\) '
        . 'REFERENCES (`[^`]*\.)?`([^`]*)` \(`([^`]*)`\)'
        . '( ON DELETE (RESTRICT|CASCADE|SET NULL|NO ACTION))?'
        . '( ON UPDATE (RESTRICT|CASCADE|SET NULL|NO ACTION))?/';
	preg_match_all($regExp, $lines[$i], $matches, PREG_SET_ORDER);
//echo "<h1>".count($matches[0])."</h1>";
	if (count($matches[0])<1) {
		$i++;
		continue;
	}
//echo "<pre>";
//var_export($matches);
//echo $lines[$i]."</pre>";
	for ($j=1; $j<count($plain); $j++) {
//echo "<h2>1".$plain[$j][0]."</h2><h2>2".$matches[0][2]."</h2>";
		if ($plain[$j][0]==$matches[0][2]) {
			array_push($plain[$j], $matches[0][4]);
			array_push($plain[$j], $matches[0][5]);	
			array_push($plain[$j], $matches[0][1]);
		} else {
//			array_push($plain[$j], "");
//			array_push($plain[$j], "");
		}
	}
}



}
//echo "Plain" .var_dump($plain);
//echo "<hr />";
//echo "POST" . var_dump($_POST);
//echo "<p>Number of fields: $fields</p>";


/* ADD FILE from FILE INPUT */
//http://www.tizag.com/phpT/fileupload.php
if ($_POST['Submit']=='Upload File') {
echo "<p>Adding...";
if ($_POST['fileName']=='') {
	$_POST['fileName'] = $_FILES['uploadedFile']['name'];
}

echo "<p>".$_POST['fileName']."</p>";

if (!validateName($_POST['fileName'], "filename")) {
	echo "</p><p class=\"error-message\">Error: File name contains at least 1 illegal character or is not .xsd";
	$error_exists = true;
} else if (!in_array($_POST['fileName'], $files)) {
	$target_path = $schema_path . $_POST['fileName'];
	if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $target_path)) {
		echo "...Done</p>";
	} else {
		echo "</p><p class=\"error-message\">Error: There was an error uploading the file; please try again.</p>";
		$error_exists = true;

	}
} else {
	echo "</p><p class=\"error-message\">Error: Unable to add file (\"" . $_POST['fileName'] . "\"); file already exists</p>";
        $error_exists = true;

}

}

/* SWITCH from FILE INPUT */
if ($_POST['Switch']=='Plain Text Input' && $_FILES['uploadedFile']['name']!='') {
if ($_POST['fileName']=='') {
	$_POST['fileName'] = $_FILES['uploadedFile']['name'];
}
$edit_selected = $_POST['fileName'];
$target = $_FILES['uploadedFile']['tmp_name'];

}


/* ADD or EDIT FILES CONTENTS from PLAIN INPUT*/
if ($_POST['Submit']=='Add File' || $_POST['Submit']=='Add New File' || $_POST['Submit']=='Save File') {

$in = in_array($_POST['fileName'], $files);

if ($_POST['Submit']=='Add File' || $_POST['Submit']=='Add New File') {
	echo "<p>Adding...";
} else {
	echo "<p>Saving...";
}

$valid = validateName($_POST['fileName'],"filename");

if ((($_POST['Submit']=='Add File' && !$in) || 
	($_POST['Submit']=='Add New File' && !$in) ||
	($_POST['Submit']=='Save File' && $in)) &&
	($_POST['fileName']!='') &&
	$valid	){
	$all_correct = true;
} else $all_correct = false;

if ($all_correct) {
$fp = fopen($schema_path . $_POST['fileName'], "w");
if ($fp) {
	fwrite($fp, $_POST['plain_text']);
	fclose($fp);
	echo "...Done</p>";
} else {
 $all_correct = false;
}

}
if (!$all_correct) {
	echo "</p><p class=\"error-message\">Error: ";

	if (!$valid) {
		echo "File name contains at least 1 illegal character or is not the right extension";
	}else if ($_POST['fileName'] == ''){
		echo "Name of schema file must be filled in.";
	} else if ($_POST['Submit']=='Add File' || $_POST['Submit']=='Add New File') {
	 echo "Unable to add file (\"" . $_POST['fileName'] . "\"); file already exists.";
	} else if ($_POST['Submit']=='Save File') {
	 echo "Unable to save file (\"" . $_POST['fileName'] . "\"); file does not exist.";
	} else if (!$fp) {
                echo "Unable to action; please try again.";
        }

	echo "</p>\n";
	if ($_POST['Submit']=='Add New File' || $_POST['Submit']=='Save File') {
		$edit_selected = $_POST['fileName'];
	}
	$error_exists = true;
	
}

}


/* DELETE TABLES*/
else if ($_POST['DeleteSelected']=='Drop Selected Tables') {
echo "<p>Deleting...</p>";
$delete_values = $_POST['delete_'];
//echo var_dump($delete_values);
if (!empty($delete_values)) {
	for ($i=0; $i<count($delete_values); $i++) {
		if (in_array($delete_values[$i], $admin_tables)) {
			echo "<p class=\"error-message\">Error: Unable to drop administrative tables</p>";
			continue;
		}
		$sql = "DROP TABLE " . mysql_real_escape_string($delete_values[$i]);
		showQuery($sql);
		if (mysql_query($sql)) {
			echo "<p>Deleted table " . $delete_values[$i] . ",</p>";
		} else {
			echo "</p><p class=\"error-message\">Error: Unable to delete table</a>";
			$error_exists = true;
			break;
		}
	}
}
if (!$error_exists) {
	echo "<p>...Done</p>\n";
}


/* DELETE SCHEMA FILES */
} else if ($_POST['DeleteSelected']=='Delete Selected Schema Files') {
echo "<p>Deleting...</p>";
$delete_values = $_POST['delete_'];
if (!empty($delete_values)) {
	for ($i=0; $i<count($delete_values); $i++) {
		$output = shell_exec('rm "' . $schema_path . $files[$delete_values[$i]].'"');
	}
}
echo "<p>...Done</p>\n";



/* Generate tables based off files */
} else if ($_POST['Submit']=='Create Table') {
	echo "<p>Creating tables...</p>";
$create_tables = $_POST['delete_'];
if (!empty($create_tables)) {
	for ($i=0; $i<count($create_tables); $i++) {
		$target_path = $schema_path . $files[$create_tables[$i]];
		$cmd = "perl " . $schema_parser . " -a '" . $target_path ."' -v 2>&1";	
		$output = shell_exec($cmd);
		showQuery($output);
	}
}
echo "<p>...Done</p>\n";
}




echo "<form ";
if ($_GET['input']=='file') {
	echo "enctype='multipart/form-data' ";
}
echo " action='eSchema.php?input=" . $_GET['input'] . "' method='post'>\n";


/* Print sub navigation */
echo "<div class='sub-navigation'>";
/* For Plain Text input */
if (!($edit_selected!='' && $_GET['input']!='') || ($edit_selected!='' && $_GET['input']=='')) {
	echo "<input name='Switch'";
	if ($_GET['input'] == '' || $_GET['input']=='Plain Text Input') {
		echo " class='selected'";
	}
	echo " type='Submit' value='Plain Text Input' />\n";
}
/* For File input */
if ($edit_selected=='' && !($_GET['input']=='' && $error_exists)) {
	echo "<input name='Switch'";
	if ($_GET['input'] == 'file') {
		echo " class='selected'";
	}
	echo " type='Submit' value='File Input' />\n";
}
/* For Form input */
if (!(($edit_selected!='' || $error_exists==true) && $_GET['input']!='form')) {
	echo "<input name='Switch'";
	if ($_GET['input']=='form') {
		echo " class='selected'";
	} 
	echo " type='Submit' value='Form Input' />\n";
}
echo "<input name='Switch' type='Submit' value='Cancel' />\n";

echo "</div>";


if ($_GET['input']=='file') {

/* INPUT TABLE: File Input */
echo "<table class='file-input'>\n";
echo "<tr><td>Name of File (include .xsd extension)</td>\n";
echo "<td><input type='text' name='fileName' ";
if ($error_exists) {
        echo "value='" . $_POST['fileName'] . "' ";
}
echo "/></td></tr>\n";
echo "<tr><td>Choose a file to upload:</td>\n";
echo "<td><input name='uploadedFile' type='file' /></td></tr>\n";
echo "</table>\n";
echo '<p>If the name of the file is blank, the schema file will be saved 
	with its original name. File names can only
	include letters, numbers, underscores, dashes or periods. Table names
	can only include letters (a-z). </p>';
echo "<p><input type='Submit' name='Submit' value='Upload File' /></p>";




/* INPUT TABLE: Form input*/
} else if ($_GET['input']=='form') {


if ($fields<1) $fields=2;
echo "<table class=\"form-input\">\n";
echo "<tr><td colspan=\"1\"><strong>Name of Table</strong></td>\n";
echo "<input type='hidden' value='".$_POST['origTableName']."' name='origTableName' />\n";
echo "<td colspan=\"1\"><input type='text' value='$plain[0]' name='tableName' />";
echo "</td></tr>\n";

echo "<tr><td colspan=\"2\"><strong>Fields</strong></td></tr>\n";

echo "<tr><td>Select the checkboxes for the rows to delete:</td>\n";
echo "<td><input type='submit' name='Submit2' value='Delete Selected Rows' /></td></tr>\n";
echo "<tr><td>Input the number of rows you need to add more fields: </td>\n";
echo "<td><input type='textbox' value='1' name='add_fields' /><input type='submit' value='Add Rows' name='Submit2' /></td></tr>\n";
echo "<tr><td colspan='2'>";
echo "<table class='display'><thead><th></th><th>Field Name</th><th>Field Type</th><th>Field Flags</th><th>PK</th><th>Foreign Table</th><th>Foreign Field</th></thead><tbody>";
echo "<input type='hidden' name='num_fields' value= '$fields'/>";
/* For the first column which is needed to update data itself in the Edit Data page */
echo "<tr><td></td><td>ID</td><td>int(11)</td><td>UNIQUE NOT NULL AUTO_INCREMENT</td><td></td><td></td><td></td></tr>\n";
for ($i=1; $i<$fields; $i++) {
	echo "<tr><td><input type='checkbox' name='fDel[]' value='".$i."' /></td>";
	echo "<td><input type='text' value='".$plain[$i+1][0]
	."' name='fName_".$i."' /></td>\n";
	echo "<input type='hidden' value='".$_POST['foName_'.$i]."' name='foName_".$i."' />";
	echo "<td><input type='text' value='".$plain[$i+1][1]
	."' name='fType_".$i."' /></td>\n";
	echo "<td><input type='text' value='".$plain[$i+1][2]
	."' name='fFlag_".$i."' /></td>\n";
//echo $plain[$i+1][3];
	echo "<td><input type='checkbox' value='".$plain[$i+1][3]."' ";
	if (substr($plain[$i+1][3],strpos($plain[$i+1][3],"-"))=="-PK") 
		echo "checked='yes' ";
	echo "name='fPK[]' /></td>\n";
	echo "<td><input type='text' value='".$plain[$i+1][4]
        ."' name='fFTab_".$i."' /></td>\n";
	echo "<td><input type='text' value='".$plain[$i+1][5]
        ."' name='fFCol_".$i."' /></td></tr>\n";
	echo "<input type='hidden' value='".$plain[$i+1][6]
	."' name='fFCon_".$i."' />";
}
echo "</td></tr>";
echo "</table></td></tr>";
echo "</table>";
echo "<p><input type='submit' value='Add New Table' name='Submit' /></p>";



/* INPUT TABLE: Plain Text Input*/
} else {
echo "<table class='plain-input'>\n";
echo "<tr><td>Name of Schema File (please include .xsd extension)</td>\n";
echo "<td class='align-right'><input type='text' name='fileName' ";
if ($edit_selected != '') {
	echo 'value="' . $edit_selected . '" ';
} else if ($error_exists) {
	echo 'value="' . $_POST['fileName'] . '" ';
}
echo "/></td></tr>\n";
echo "<tr><td colspan='2'><br /><textarea name='plain_text' rows='10' cols='60'>";
if ($error_exists) {
	echo $_POST['plain_text'];
} else if ($edit_selected != '') {
	$output = shell_exec('cat "' . $target . '"');
	echo $output;
}
echo "</textarea></td></tr>\n";
echo "</table>\n";
echo "<p>The Name of Schema File  must be filled. File names can only include letter (a-z), numbers, underscores, dashes, or periods. </p>\n";

if ($edit_selected != '' && $_POST['Switch']!='Plain Text Input') {
	echo "<p><input type='Submit' name='Submit' value='Save File' /> ";
	echo "<input type='Submit' name='Submit' value='Add New File' /></p>";
} else {
	echo "<p><input type='Submit' name='Submit' value='Add File' /></p>";
}


} /* end else for Plain Text input*/
echo "</form>\n";



?>


<?php

//echo "<pre>" . var_export($files) . "</pre>";

echo "<table class=\"presentation\"><tr><td>";

/* DISPLAY TABLE of available tables */

$sql ="SHOW TABLES FROM $mysql";
$sql ="SELECT table_name,create_time FROM INFORMATION_SCHEMA.TABLES WHERE table_schema='$mysql'";
$result = mysql_query($sql);
if (!$result) {
	die("DB Error, could not list tables\n");
}

echo "<form action='eSchema.php?input=" . $_GET['input'] . "' method='POST'>\n";
echo "<div class=\"scrollableContainer\" style=\"width:" . (135 + (149*2)) . "px\">\n";
echo "<div class=\"scrollingArea\">\n";
echo "<table class=\"display scrollable\">\n";
echo "<thead>\n";
echo "<tr><th class=\"check-box\"><div></div></th>\n";
echo "<th class=\"other-submit\"><div></div></th>\n";
echo "<th class=\"field\"><div>Table Name</div></th>\n";
echo "<th class=\"field\"><div>Date Created</div></th></tr>\n";
echo "</thead><tbody>\n";
while ($row = mysql_fetch_row($result)) {
    if (!in_array($row[0], $admin_tables)) {
        echo "<tr>\n";

	/* Check box to select and delete */
        echo "<td class=\"check-box\"><div><input type='checkbox' ";
	if ($_POST['Selected']=='Select All') {
		echo "checked='yes' ";
	}
	echo "name='delete_[]' value='".$row[0]."' /></div></td>\n";

	/* Submit button to Edit File */
        echo "<td class=\"other-submit\"><div><input type='submit' name='edit_". $row[0] ."' value='Look Up' /></div></td>\n";
	echo "<td class=\"field\"><div>" . $row[0] . "</div></td>";
	echo "<td class=\"field\"><div>" . $row[1] . "</div></td>";
        echo "</tr>\n";
    }
}
echo "</tbody></table>\n";
echo "</div></div>\n";


echo "</td><td>";
//echo "<div class=\"side\">";

/* DISPLAY TABLE of schema files */

/* Get schema files currently availiable from the file ID and create a hash
        table where the file ID make to the file name */
$output = shell_exec('ls -1i "' . $schema_path . '" | grep ".\.xsd$"');
$plain2 = preg_split("/[\n]+/", $output, -1, PREG_SPLIT_NO_EMPTY);
unset($files);
foreach ($plain2 as &$value){
        $value = trim($value);
         $files[substr($value, 0, strpos($value, " "))] = substr(strstr($value," "),1);
}


$output = shell_exec('ls -l --time-style=long-iso "' . $schema_path . '" | grep ".\.xsd$" |  sed "s/ * / /g" | cut -d " " -f 6,7');
//echo "<pre>" . $output . "</pre>";
$plain = preg_split("/[\n]+/", $output, -1, PREG_SPLIT_NO_EMPTY);
//echo "<pre>" . var_export($plain) . "</pre>";

echo "<div class=\"scrollableContainer\" style=\"width:" . (99 + (149*2)) . "px\">\n";
echo "<div class=\"scrollingArea\">\n";
echo "<table class=\"display scrollable\">\n";
echo "<thead>\n";
echo "<tr><th class=\"check-box\"><div></div></th>";
echo "<th class=\"edit-submit\"><div></div></th>";
echo "<th class=\"field\"><div>Schema File Name</div></th>";
echo "<th class=\"field\"><div>Date Modified</div></th></tr>\n";
echo "</thead><tbody>\n";
$i=0;
while (list($key, $value) = each($files)) {

	echo "<tr>\n";
	echo "<td class=\"check-box\"><div><input type='checkbox' ";
        if ($_POST['Selected']=='Select All') {
                echo "checked='yes' ";
        }
        echo "name='delete_[]' value='".$key."' /></div></td>\n";
        echo "<td class=\"edit-submit\"><div><input type='submit' name='edit_".$key."' value='Edit' /></div></td>";
	echo "<td class=\"field\"><div>". $value."</div></td>";
 	echo "<td class=\"field\"><div>" . $plain[$i] . "</div></td>\n";
        echo "</tr>\n";
	$i++;
}
echo "</tbody>\n";
echo "</table>\n";
echo "</div></div>\n"; /* Close divs for scrolling */

echo "</td></tr><tr><td>\n";


echo "<input type='submit' name='Selected' value='Select All' />";
echo "<input type='submit' name='DeleteSelected' value='Drop Selected Tables' />";

echo "</td><td>";

echo "<input type='submit' name='DeleteSelected' value='Delete Selected Schema Files' />";
echo "<input type='submit' name='Submit' value='Create Table' />";

echo "</td></tr></table>";

echo "</form>\n";

require('footer.inc.php');
?>


